#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File    :   crusade.py
@Time    :   2020/11/27
@Author  :   wenke wang
@Version :   1.0
@Desc    :   CRUSADE出血评估
'''

# here put the import lib
import math, sys, os, json
from decimal import Decimal
from crusade_eval_param import CrusadeEvalParam

def get_default_settings():
    """
    获取默认的评分配置
    """
    default_setting = None

    setting_path = os.path.join(sys.path[0], "crusade_score_setting.json")
    with open(setting_path, "r", encoding="utf-8") as fp:
        default_setting = json.load(fp)
    
    return default_setting

def evaluate(param, score_settings = None):
    """
    CRUSADE出血评估
    """

    if not score_settings:
        score_settings = get_default_settings()

    precision = Decimal("0.00")
    # 血肌酐清除率
    ccr = Decimal(140 - param.age) * Decimal(param.weight) / Decimal(72 * param.scr)
    if param.gender == "F":
        ccr = ccr * Decimal("0.85")
    ccr = ccr.quantize(precision)

    total_score = 0
    # 红细胞压积得分
    total_score = total_score + [p["score"] for p in score_settings["pcv"] if Decimal(str(p["low"])) <= Decimal(param.pcv) and Decimal(str(p["high"])) > Decimal(param.pcv)][0]
    # 血肌酐清除率得分
    total_score = total_score + [c["score"] for c in score_settings["ccr"] if Decimal(str(c["low"])) < ccr and Decimal(str(c["high"])) >= ccr][0]
    # 心率得分
    total_score = total_score + [h["score"] for h in score_settings["hp"] if Decimal(h["low"]) < Decimal(param.hp) and Decimal(h["high"]) >= Decimal(param.hp)][0]
    # 性别得分
    total_score = total_score + [g["score"] for g in score_settings["gender"] if g["val"] == param.gender][0]
    # 心衰得分
    total_score = total_score + [g["score"] for g in score_settings["hf"] if g["val"] == param.hf][0]
    # 既往心血管疾病得分
    total_score = total_score + [g["score"] for g in score_settings["cvd"] if g["val"] == param.cvd][0]
    # 糖尿病得分
    total_score = total_score + [g["score"] for g in score_settings["dm"] if g["val"] == param.dm][0]
    # 收缩压得分
    total_score = total_score + [h["score"] for h in score_settings["sbp"] if Decimal(h["low"]) < Decimal(param.sbp) and Decimal(h["high"]) >= Decimal(param.sbp)][0]

    risk = [r["val"] for r in score_settings["risk"] if r["low"] <= total_score and r["high"] >= total_score][0]
    return { "score": total_score, "risk": risk }

if __name__ == "__main__":
    param = CrusadeEvalParam(68, 'M', 60, 36.2, 0.96, 78, 1, 1, 1, 168)
    result = evaluate(param)
    print(result)

